<template>
  <div class="userEdit-img">
    <img :src="img" class="Edit-img" ref="images">
   <div class="areYouSure">
    <div class="left-cancel" @click="$emit('close')">取消</div>
    <div class="right-complete" @click="onComplete">完成</div>
   </div>
  </div>
</template>

<script>
import { editUserPhoto } from '@/service/getDate'
// 导入裁剪包样式
import 'cropperjs/dist/cropper.css'
// 导入裁剪的包
import Cropper from 'cropperjs'
export default {
   name: 'userEditImgPage',
   data () {
    return {
      cropperImg: null, //裁剪后的图片
    }
   },
   mounted() {
    const imagesDom = this.$refs.images
    this.cropperImg = new Cropper(imagesDom, {
      viewMode:1,
      dragMode: 'move',
      aspectRatio: 1, // 纵横比 定义裁剪框的固定长宽比。默认情况下，裁剪框具有空闲比率
      autoCropArea: 1, // 它应该是0到1之间的一个数字。定义自动裁剪面积大小(百分比)。
      cropBoxMovable: false, // 是否允许通过拖动移动裁剪框。
      cropBoxResizable: false, // 是否允许通过拖动调整裁剪框的大小
      background: false, // 是否显示本身的背景样式
      movable: true //  启用移动图像。
      })
   },
   props: {
    img: {
      type: [Object, String],
      required: true
    }
   },
   methods: {
    onComplete() {
      this.cropperImg.getCroppedCanvas().toBlob(blob => {
        console.log(blob);
        this.uploadUserPhoto(blob)
      })
    },
   async uploadUserPhoto(blob) {
    const formData = new FormData()
    formData.append('photo',blob)
      try {
        const {data} = await editUserPhoto(formData)
        this.$emit('user-photo', data)
        this.$emit('close')
      } catch(err) {
        console.log(err);
      }
    }
   },
}
</script>

<style lang="scss" scoped>
  .userEdit-img {
    height: 100%;
    // line-height: 100%;
    background: #333;
    .Edit-img {
      max-width: 100%;
      display: block;
    }
     .areYouSure {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      display: flex;
      justify-content: space-between;
      z-index: 1111;
      font-size: 35px;
      color: #fff;
      padding: 30px;
      .left-cancel,.right-complete {
        display: flex;
        justify-content: center;
        line-height: 50px;
        width: 120px;
        height: 60px;
        border: 1px solid #fff;
      }
    }
  }
</style>